import { ADD_BROWSE_RECORD, DEL_BROWSE_ITEM, CLEAR_ALL_BROWSE } from '../types'
import { getStore, setStore, removeStore } from '@/utils/mUtils'

const MY_BROWSE_LIST = 'MY_BROWSE_LIST'
const state = {
	// 获取本地数据
	browseList: getStore(MY_BROWSE_LIST)?JSON.parse(getStore(MY_BROWSE_LIST)):[]
}

const actions = {
	addBrowse ({commit}, data) {
		commit(ADD_BROWSE_RECORD, data)
	},
	delBrowseItem ({commit}, data) {
		commit(DEL_BROWSE_ITEM, data)
	},
	clearBrowse ({commit}) {
		commit(CLEAR_ALL_BROWSE)
	}
}

const getters = {
	browseList: state => {
		return state.browseList
	}
}

const mutations = {
	// 添加浏览记录
	[ADD_BROWSE_RECORD] (state, data) {
		let maxLen = 20
		let item = state.browseList.find(n=>n._id == data._id)
		if (!item && state.browseList.length <= maxLen) {
			state.browseList.unshift({
				_id: data._id,
				goodsName: data.goodsName,
				goodsCover: data.goodsCover,
				price: data.price
			})	
		}else if (state.browseList.length >= maxLen) {
			state.browseList.shift()
		}
		setStore(MY_BROWSE_LIST, JSON.stringify(state.browseList))
	},
	// 删除单条浏览记录
	[DEL_BROWSE_ITEM] (state, data) {
		state.browseList.forEach((n, i) => {
			if (n._id == data._id) {
				state.browseList.splice(i, 1)
				setStore(MY_BROWSE_LIST, JSON.stringify(state.browseList))
			}
		})
	},
	// 清空全部浏览记录
	[CLEAR_ALL_BROWSE] (state) {
		state.browseList = []
		removeStore(MY_BROWSE_LIST)
	}
}

export default {
	state,
	getters,
 	mutations,
 	actions
}
